package saleMarket.controller.basic;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import saleMarket.domain.Logistics;
import saleMarket.domain.Order;
import saleMarket.service.LogisticsService;
import saleMarket.service.OrderService;
import util.Condition;
import util.ControllerHelper;
import util.JSONUtil;
import util.Pagination;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Slf4j
@WebServlet("/order.ctl")
public class OrderController extends HttpServlet {
    /**
     * GET, http://localhost:8080/order.ctl?id=1, 查询id=1的项目
     * GET, http://localhost:8080/order.ctl, 查询所有的项目
     * 把一个或所有类别对象响应到前端
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response)
            throws ServletException, IOException {
        //创建JSON对象respMessage_jsonObj，以便往前端响应信息
        JSONObject respMessage_jsonObj = new JSONObject();
        Object id_obj = request.getParameter("id");
        try {
            //如果id_Obj != null, 说明请求数据有id键，是请求某个Logistics对象
            if (id_obj != null) {
                int id_int = Integer.parseInt(id_obj.toString());
                responseOrder(id_int, response);
            } else {
                responseOrders(response);
            }
        } catch (SQLException e) {
            respMessage_jsonObj.put("message", "数据库操作异常");
            e.printStackTrace();
            //响应respMessage_jsonObj到前端
            response.getWriter().println(respMessage_jsonObj);
            //打印异常栈，方便调试
            log.error(e.getMessage(),e);
        } catch (Exception e) {
            respMessage_jsonObj.put("message", "网络异常");
            //响应respMessage_jsonObj到前端
            response.getWriter().println(respMessage_jsonObj);
            //打印异常栈，方便调试
            log.error(e.getMessage(),e);
        }
    }

    //按分页信息响应符合条件的对象和对象总数
    private void responseOrders(HttpServletResponse response)
            throws ServletException, IOException, SQLException {
        //分页获得满足条件的所有对象
        Collection<Order> orders=
                OrderService.getInstance().findAll();
        //第二个参数可以防止循环引用
        String order_jsonStr = JSON.toJSONString(orders,
                SerializerFeature.DisableCircularReferenceDetect);
        response.getWriter().println(order_jsonStr);

    }
    //响应一个对象
    private void responseOrder(int id, HttpServletResponse response)
            throws IOException, SQLException {
        Collection<Order> orders= new ArrayList<>();
        //根据id查找
        Order order =
                OrderService.getInstance().find(id);
       orders.add(order);
        //第二个参数可以防止循环引用
        String order_jsonStr = JSON.toJSONString(orders,
                SerializerFeature.DisableCircularReferenceDetect);
        response.getWriter().println(order_jsonStr);
        //响应到前端
        response.getWriter().println(order_jsonStr);
    }

    /**
     * POST, http://localhost:8080/order.ctl, 增加项目
     * 增加一个项目对象：将来自前端请求的JSON对象，增加到数据库表中
     * @param request 请求对象
     * @param response 响应对象
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        String GP_json = JSONUtil.getJSON(request);
        //将JSON字串解析为对象
        Order orderToAdd = JSON.parseObject(GP_json,Order.class);
        //创建JSON对象message，以便往前端响应信息
        JSONObject message = new JSONObject();
        //在数据库表中增加Logistics对象
        try {
            if(OrderService.getInstance().add(orderToAdd)) {
                message.put("message", "增加成功");
            }else {
                message.put("message", "增加失败");
            }
        } catch (SQLException e) {
            message.put("message", "数据库操作异常");
            //打印异常栈，方便调试
            log.error(e.getMessage(),e);
        } catch (Exception e) {
            message.put("message", "网络异常");
            //打印异常栈，方便调试
            log.error(e.getMessage(),e);
        }
        //响应message到前端
        response.getWriter().println(message);
    }
    
    /**
     * DELETE, http://localhost:8080/order.ctl?id=2, 删除id=2的项目
     * 删除一个项目对象：根据来自前端请求的id，删除数据库表中id的对应记录
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response) 
            throws IOException {
        //从JSONObject对象中读取键“id”的值（Java Object对象），
        Object id_obj = request.getParameter("id");
        int id_int = Integer.parseInt(id_obj.toString());
        //创建JSON对象respMessage_jsonObj，以便往前端响应信息
        JSONObject respMessage_jsonObj = new JSONObject();
        try {
            //到数据库表中删除对应的Logistics
            if(OrderService.getInstance().delete(id_int)) {
                respMessage_jsonObj.put("message", "删除成功");
            }else {
                respMessage_jsonObj.put("message", "删除失败");
            }
        } catch (SQLException e) {
            respMessage_jsonObj.put("message", "数据库操作异常");
            //打印异常栈，方便调试
            log.error(e.getMessage(),e);
        } catch (Exception e) {
            respMessage_jsonObj.put("message", "网络异常");
            //打印异常栈，方便调试
            log.error(e.getMessage(),e);
        }
        //响应respMessage_jsonObj到前端
        response.getWriter().println(respMessage_jsonObj);
    }
    /**
     * PUT, http://localhost:8080/order.ctl, 修改项目
     *
     * 修改一个项目对象：将来自前端请求的JSON对象，更新数据库表中相同id的记录
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPut(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        //根据request对象，获得代表参数的JSON字串
        String order_json = JSONUtil.getJSON(request);
        //将JSON字串解析为Logistics对象
        Order orderToUpdate = JSON.parseObject(order_json, Order.class);
        //创建JSON对象message，以便往前端响应信息
        JSONObject message = new JSONObject();
        //到数据库表修改Logistics对象对应的记录
        try {
            if(OrderService.getInstance().update(orderToUpdate)) {
                message.put("message", "修改成功");
            }else {
                message.put("message", "修改失败");
            }
        } catch (SQLException e) {
            message.put("message", "数据库操作异常");
            //打印异常栈，方便调试
            log.error(e.getMessage(),e);
        } catch (Exception e) {
            message.put("message", "网络异常");
            //打印异常栈，方便调试
            log.error(e.getMessage(),e);
        }
        //响应message到前端
        response.getWriter().println(message);
    }
}